<template>
  <div class="watermark-container" ref="container">
    <slot></slot>
  </div>
</template>

<script lang="ts" setup>
import { useWatermarkBg } from '@/hooks/useWatermark'
import { WatermarkPropType } from '@/types/props/watermark'
import { ref, reactive, onMounted, onUnmounted } from 'vue'

const props = withDefaults(defineProps<WatermarkPropType>(), {
  fontsize: 16,
  color: 'rgba(0, 0, 0, 0.3)',
  gap: 10
})

const container = ref<HTMLDivElement>()
const { base64, size } = useWatermarkBg(props).value

let div: HTMLDivElement | null = null
const generateWatermark = () => {
  if (div) {
    div.remove()
  }
  div = document.createElement('div')
  div.style.backgroundImage = `url(${base64})`
  div.style.backgroundSize = `${size}px ${size}px`
  div.style.backgroundRepeat = 'repeat'
  div.style.position = 'absolute'
  div.style.zIndex = '9999'
  div.style.pointerEvents = 'none'
  div.style.inset = '0'
  container.value?.appendChild(div)
}

const ob = new MutationObserver(entries => {
  for (const entry of entries) {
    for (const node of entry.removedNodes) {
      if (node === div) {
        generateWatermark()
      }
    }
    if (entry.target === div) {
      generateWatermark()
    }
  }
})

onMounted(() => {
  generateWatermark()
  ob.observe(container.value!, {
    childList: true,
    subtree: true,
    attributes: true
  })
})

onUnmounted(() => {
  ob.disconnect()
})
</script>

<style lang="scss" scoped>
.watermark-container {
  position: relative;
  width: fit-content;
}
</style>
